"ui";
ui.layout(
    <vertical bg="#ffffff" gravity="center" clickable="true">
        <text textStyle="bold" marginTop="-100" w="auto" h="100" text="小能手(1.0.0)" color="#4e6ef2" textSize="30" />

        <button h="55" w="320" marginTop="20" id="plug" bg="#4e6ef2" textSize="14sp" textStyle="bold" textColor="#f5f5f5" text="插件: 未安装" />
        <button h="55" w="320" marginTop="20" id="member" bg="#4e6ef2" textSize="14sp" textStyle="bold" textColor="#f5f5f5" text="会员: 未激活" />
        <button h="55" w="320" marginTop="20" id="device" bg="#4e6ef2" textSize="14sp" textStyle="bold" textColor="#f5f5f5" text="显示设备码" />
        <button h="55" w="320" marginTop="20" id="start" bg="#4e6ef2" textSize="14sp" textStyle="bold" textColor="#f5f5f5" text="启动" />
        <button h="55" w="320" marginTop="20" id="close" bg="#4e6ef2" textSize="14sp" textStyle="bold" textColor="#f5f5f5" text="关闭" />
    </vertical>
);

const APP_PACKAGE = "com.rinzz.avatar";

let running = false;

//检测无障碍模式
auto();
//保持屏幕常量
device.keepScreenOn();

threads.start(function () {
    let isInstall = isAppInstalled(APP_PACKAGE);
    if (isInstall) {
        ui.run(function () {
            ui.plug.setText('插件: 已安装');
        });
    }
});

threads.start(function () {
    let deviceId = device.getIMEI();
    if (deviceId == null) {
        deviceId = device.getAndroidId();
    }
    //获取绑定状态
    let res = http.get("http://dy.leyouhome.cn/api/active/check?code=" + deviceId);
    if (res.statusCode == 200) {
        let resp = JSON.parse(res.body.string());
        if (resp.code == 10000) {
            ui.run(function () {
                ui.member.setText('会员: ' + resp.data);
            });
        }
    }
});

/**
 * 展示设备码
 */
ui.device.click(() => {
    showImei();
});

/**
 * 运行脚本
 */
ui.start.click(() => {
    if (running) {
        toast('脚本已开始运行，请勿重复点击!');
        return;
    }
    threads.start(function () {
        let deviceId = device.getIMEI();
        if (deviceId == null) {
            deviceId = device.getAndroidId();
        }
        //获取绑定状态
        let res = http.get("http://dy.leyouhome.cn/api/active/check?code=" + deviceId);
        if (res.statusCode == 200) {
            let resp = JSON.parse(res.body.string());
            if (resp.code == 10000) {
                let intent = new Intent();
                let data = android.net.Uri.parse("com.rinzz.avatar://test");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setData(data);
                context.startActivity(intent);
            } else if (resp.code == 50001) {
                let password = rawInput("请输入激活码", "");
                let res1 = http.get("http://dy.leyouhome.cn/api/active/device?code=" + deviceId + "&identity=" + password);
                if (res1.statusCode == 200) {
                    let resp1 = JSON.parse(res1.body.string());
                    log(resp1);
                    if (resp1.code == 10000) {
                        let intent = new Intent();
                        let data = android.net.Uri.parse("com.rinzz.avatar://test");
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        intent.setData(data);
                        context.startActivity(intent);
                    } else {
                        toast(resp1.message);
                    }
                } else {
                    toast('网络连接异常');
                }
            } else {
                toast(resp.message);
            }
        } else {
            toast('网络连接异常');
        }
    });
});

/**
 * 停止脚本
 */
ui.close.click(() => {
    threads.start(stop);
});

// ui.download.click(() => {
//     threads.start(function () {
//         downloadApk();
//     })
// });

/**
 * 停止运行清空信息
 */
function stop() {
    engines.stopAll();
}

/**
 * APP是否安装
 * @param {*} packageName 
 */
function isAppInstalled(packageName) {
    let pm = context.getPackageManager();
    let installed = false;
    try {
        pm.getPackageInfo(packageName, android.content.pm.PackageManager.GET_ACTIVITIES);
        installed = true;
    } catch (e) {
        installed = false;
    }
    return installed;
}

events.on("exit", function () {

});

/**
 * 判断手机是否拥有root权限
 */
function checkRootPathSU() {
    let f = null;
    let kSuSearchPaths = ["/system/bin/", "/system/xbin/", "/system/sbin/", "/sbin/", "/vendor/bin/"];
    try {
        for (let i = 0; i < kSuSearchPaths.length; i++) {
            f = new java.io.File(kSuSearchPaths[i] + "su");
            if (f != null && f.exists()) {
                return true;

            }
        }
    } catch (e) {
        log(e);
    }
    return false;
}

function downloadApk() {
    try {
        let path = "http://phone.leyouhome.cn/magic.apk";

        let url = new java.net.URL(path);
        let urlConn = url.openConnection();
        urlConn.setRequestMethod("GET");
        urlConn.setDoOutput(true);
        urlConn.connect();

        let inputStream = urlConn.getInputStream();
        let file = new java.io.File('/sdcard/Download/magic.apk');
        let outStream = new java.io.FileOutputStream(file);
        let buffer = util.java.array('byte', 256);
        let len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }

        outStream.flush();
        outStream.close();
        inputStream.close();

        return true;
    } catch (e) {
        log(e);
        return false;
    }
}

/**
 * 显示设备码
 */
function showImei() {
    let deviceId = device.getIMEI();
    if (deviceId == null) {
        deviceId = device.getAndroidId();
    }
    alert('您的设备码是: ' + deviceId);
}